import { Toast } from "antd-mobile"
import {reqregister} from "../../request/api"

//状态
const initState ={
    user:{
        phone:"",
        password:"",
        nickname:""
    }
}

//actionType
const TYPES={
    REGISTER_CHANGE_USER: "REGISTER_CHANGE_USER"
}

//修改state reducer
const reducer = (state=initState,action)=>{
    switch(action.type){
        case TYPES.REGISTER_CHANGE_USER:
            return {
                ...state,
                user:{
                    ...state.user,
                    [action.key]:action.value
                }
            };
        default:
            return state;
    }
}

//逻辑和异步actions actionCreators
export const actions={
    changeUser:(key,value) =>({type:TYPES.REGISTER_CHANGE_USER,key,value}),
    doRegister:(push)=>{
        return (dispatch,getState)=>{
            let user=getUser(getState())

            reqregister(user).then(d=>{
                if(d.data.code===200){
                    Toast.show({
                        content:d.data.msg
                    })
                    push("/Login")
                }else{
                    Toast.show({
                        content:d.data.msg
                    })
                }
            })
        }
    }
}

//导出数据 Selectors
export const getUser=state=>state.register.user;

//导出reducer 
export default reducer;